#include "mystdio.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>


Myfile * Mybuyfile(int fd,int flag)
{
   Myfile * f=(Myfile*) malloc(sizeof(myfile));
   if(f==NULL)  return NULL;
   f->flag=flag;
   f->myfilno=fd;
   f->flushmeth=LINE_FLUSH;
   memset(f->buffer,0,sizeof(f->buffer));
   return f;
}
Myfile * Myfopen(const char *path,const char *mode)
{
     int fd=-1;
     int flag=0;
     if(strcmp(mode,"w")==0)
     {
       flag= O_CREAT | O_WRONLY | O_TRUNC;
      fd=open(path,flag,0666);
     }
     else if(strcmp(mode,"a")==0)
     {
      flag= O_CREAT | O_WRONLY | O_APPEND;
      fd=open(path,flag,0666);
     }
     else if(strcmp(mode,"a")==0)
     {
      flag=O_RDWR;
      fd=open(path,flag);
     }
    
     else{
      //>>>>>>>>;
     }
     if(fd<0)
     {
      return NULL;
     }
     return Mybuyfile(fd,flag);
}
void Myclose(Myfile * file)
{
  if(file->myfilno <0) return ;
  Myflush(file);
  close(file->myfilno);
  free(file);
}

int Mywrite(Myfile *file,void *str,int len)
{
  memcpy(file->buffer+file->bufflen,str,len);
  if(file->flushmeth & LINE_FULSH) &&file->buffer[file->bufflen-1]=='\n')
  {
      Myflush(file);
  }
  return 0;
}

void Myflush(Myfile *file)
{
  if(file->bufflen<=0)  return ;
   int n=write(file->myfilno,file->buffer,filr->bufflen);
   void(n);
   fsync(file->myfilno);
   file->bufflen=0;

}
